import _ from 'underscore'
import dispatcher from 'lib/dispatcher'
import {Scope} from 'lib/scopeFactory'

import TimeStore from 'lib/stores/time-store'
import {coreApi,sortMap,parseToChart,parseToTopbar} from '../apis/core-util'
import basicInfo from '../apis/basicInfo'

import relate from 'lib/geoJSON/province_relation'

export default class MainScope extends Scope {
  constructor(props){
    super();
    this.regionId = props.routeParams.regionId
    this.countryId = props.routeParams.countryId

    this.props = props;
    this.$state = {
      title:'',
      geoKey:null,
      chartGeo:{
        loading:true
      },
      chart0:{
        loading:true
      },
      chart1:{
        loading:true
      },
      chart2:{
        loading:true
      },
      chart3:{
        loading:true
      },
      geoLegend:{
        align:'right',
        layout:'vertical'
      },
      cityCode: undefined
    }

    this.setGeoTitle = this.setGeoTitle.bind(this);
    this.setGeoTitle(props);

    this.geoApi = coreApi({
      limit:null,
      size:1
    },TimeStore.getValue,() => {
      return {
        classify:'citycode',
        countryCodeId:BlueWare.countryId,
        regionCodeId:this.regionId
      }
    },function(){
      return {
        viewKey:this.props.viewKey,
        order:sortMap[this.props.viewKey]
      }
    }.bind(this),function(){
      if(this.props.viewKey==='avg_resp'||this.props.viewKey==='thp'){
        return {
          urlName:'httptransaction',
          classifyKeyField:'time',
          classifyCountField:'num'
        }
      }else if(this.props.viewKey==='total_receive_size'){
        return {
          urlName:'httptransaction',
          classifyKeyField:'receive',
          classifyCountField:'num'
        }
      }else if(this.props.viewKey==='session_count'){
        return {
          urlName:'session'
        }
      }else if(this.props.viewKey==='error_rate'){
        return {
          urlName:'errorrate'
        }
      }
    }.bind(this));

    this.basicInfo = basicInfo({
      urlName:'area'
    },() => {
      if(this.countryId&&this.regionId){
        return {
          id:this.regionId,
          parentId:this.countryId
        }
      }else{
        if(this.countryId){
          return {
            id:this.countryId,
            parentId:0
          }
        }else{
          return {
            id:this.regionId,
            parentId:BlueWare.countryId //china
          }
        }
      }
    })
    this.chart0Api = coreApi({
      limit:5,
      classify:'region',
      classifyKeyField:'time',
      classifyCountField:'num',
      viewKey:'avg_resp',
      urlName:'httptransaction'
    },TimeStore.getValue,() => {
      if(this.countryId&&this.regionId){
        return {
          countryCodeId:this.countryId,
          regionCodeId:this.regionId
        }
      }else{
        if(this.countryId){
          return {
            countryCodeId:this.countryId
          }
        }else{
          return {
            countryCodeId:BlueWare.countryId, //china
            regionCodeId:this.regionId
          }
        }
      }
    },function (){
      return {order:sortMap[this.viewKey]}
    });
    this.chart1Api = coreApi({
      limit:5,
      classify:'region',
      classifyKeyField:'time',
      classifyCountField:'num',
      viewKey:'thp',
      urlName:'httptransaction'
    },TimeStore.getValue,() => {
      if(this.countryId&&this.regionId){
        return {
          countryCodeId:this.countryId,
          regionCodeId:this.regionId
        }
      }else{
        if(this.countryId){
          return {
            countryCodeId:this.countryId
          }
        }else{
          return {
            countryCodeId:BlueWare.countryId, //china
            regionCodeId:this.regionId
          }
        }
      }
    },function (){
      return {order:sortMap[this.viewKey]}
    });
    this.chart2Api = coreApi({
      limit:5,
      classify:'region',
      viewKey:'error_rate',
      urlName:'errorrate'
    },TimeStore.getValue,() => {
      if(this.countryId&&this.regionId){
        return {
          countryCodeId:this.countryId,
          regionCodeId:this.regionId
        }
      }else{
        if(this.countryId){
          return {
            countryCodeId:this.countryId
          }
        }else{
          return {
            countryCodeId:BlueWare.countryId, //china
            regionCodeId:this.regionId
          }
        }
      }
    },function (){
      return {order:sortMap[this.viewKey]}
    });
    this.chart3Api = coreApi({
      limit:5,
      classify:'region',
      viewKey:'session_count',
      urlName:'session'
    },TimeStore.getValue,() => {
      if(this.countryId&&this.regionId){
        return {
          countryCodeId:this.countryId,
          regionCodeId:this.regionId
        }
      }else{
        if(this.countryId){
          return {
            countryCodeId:this.countryId
          }
        }else{
          return {
            countryCodeId:BlueWare.countryId, //china
            regionCodeId:this.regionId
          }
        }
      }
    },function (){
      return {order:sortMap[this.viewKey]}
    });
  }

  setGeoTitle(props) {
    var geoTitle;
    if(props.viewKey==='avg_resp'){
      geoTitle = 'HTTP 响应时间'
    }else if(props.viewKey==='thp'){
      geoTitle = '吞吐量'
    }else if(props.viewKey==='total_receive_size'){
      geoTitle = '传输数据量'
    }else if(props.viewKey==='session_count'){
      geoTitle = '活跃会话数'
    }else if(props.viewKey==='error_rate'){
      geoTitle = '网络错误率'
    }

    _.extend(this.$state, {geoTitle});
    if (this.emit) {
      this.regionId = props.routeParams.regionId;
      this.countryId = props.routeParams.countryId;
      this.props = props;

      this.fetchGeo();
      this.emit();
    }
  }

  fetchGeo() {
    var _this = this
    // debugger

    this.geoApi.fetch().then((data,params) => {
      // debugger
      let mapData = relate(_this.props.routeParams.cnCode);

      if (!mapData) {
        _this.$state.chartGeo = null;
        return;
      }

      _this.$state.geoKey = 'provinceMap-'+new Date().getTime();
      _this.$state.chartGeo = {
        mapData,
        joinBy:['name','regionName'],
        data:_.chain(parseToTopbar(data,params))
              .filter((a) => {
                // debugger
                let target = _.find(mapData.features,p=>a.name.indexOf(p.id) === 0);
                if (target) {
                  a.regionName = target.properties.name;
                  return true;
                }
                return false;
              })
              .map((p) => {
                return {
                  value:p.value,
                  fmtVal:p.fmtVal,
                  name:p.name,
                  label:p.label,
                  startTime:p.startTime,
                  endTime:p.endTime,
                  regionName:p.regionName,
                  cityCode: p.id
                };
              })
              .value()
      };
    }, (err) => {
      _this.$state.chartGeo = {
        error:err
      };
    }, (params) => {
      _this.$state.chartGeo = {
        loading:true,
        params:params
      };
      _this.emit();
    }).always(() => {
      _this.emit();
    });
  }

  fetch(){
    this.fetchGeo();

    this.fetchChartData();
  }
  fetchChartData() {
    var _this = this;

    let classify = _.isUndefined(this.$state.cityCode) ? 'region' : 'city';

    this.chart0Api.append({
      cityCodeId: this.$state.cityCode,
      classify
    }).fetch().then(function(data,params){
      _this.$state.chart0 = {
        data:parseToChart(data,params)
      }
    },function(err){
      _this.$state.chart0 = {
        error:err
      }
    },function(params){
      _this.$state.chart0 = {
        loading:true,
        params:params
      }
      _this.emit()
    }).always(function(){
      _this.emit()
    });

    this.chart1Api.append({
      cityCodeId: this.$state.cityCode,
      classify
    }).fetch().then(function(data,params){
      _this.$state.chart1 = {
        data:parseToChart(data,params)
      }
    },function(err){
      _this.$state.chart1 = {
        error:err
      }
    },function(params){
      _this.$state.chart1 = {
        loading:true,
        params:params
      }
      _this.emit()
    }).always(function(){
      _this.emit()
    });

    this.chart2Api.append({
      cityCodeId: this.$state.cityCode,
      classify
    }).fetch().then(function(data,params){
      _this.$state.chart2 = {
        data:parseToChart(data,params)
      }
    },function(err){
      _this.$state.chart2 = {
        error:err
      }
    },function(params){
      _this.$state.chart2 = {
        loading:true,
        params:params
      }
    }).always(function(){
      _this.emit()
    });

    this.chart3Api.append({
      cityCode: this.$state.cityCode,
      classify
    }).fetch().then(function(data,params){
      _this.$state.chart3 = {
        data:parseToChart(data,params)
      }
    },function(err){
      _this.$state.chart3 = {
        error:err
      }
    },function(params){
      _this.$state.chart3 = {
        loading:true,
        params:params
      }
      _this.emit()
    }).always(function(){
      _this.emit()
    });
  }
  $settime(payload){
    this.fetch()
  }
  $unload(){
  }
  $load(){
    var _this = this
    this.basicInfo.fetch().done(function(data){
      //TODO 当basicInfo查不到时应显示错误,可以在Router.transtition时加载basicInfo并判断
      if(data.result.length){
        _this.$state.title = data.result[0].name;
      }
      _this.emit()
    })
    this.fetch();
  }
  $switch_city({cityCode}) {
    if (cityCode !== this.$state.cityCode) {
      this.$state.cityCode = cityCode;
      this.fetchChartData();
    }
  }
}
